# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import myUser
from .serializers import CustomUserSerializer


# Create your views here.
# class CustomUserListCreateView(generics.ListCreateAPIView):
#     queryset = myUser.objects.all()
#     serializer_class = CustomUserSerializer

"""一、函数式编程 Function Based View"""


# @api_view(["GET", "POST"])
# def CustomUser_list(request):
#     if request.method == "GET":
#         s = CustomUserSerializer(instance=myUser.objects.all(), many=True)
#         return Response(data=s, status=status.HTTP_200_OK)
#     elif request.method == "POST":
#         s = CustomUserSerializer(data=request.data, partial=True)  # 部分更新使用 partial=True:非必填字段可以不填
#         # 反序列化，需要对数据进行校验,因为不确定前端传递过来的数据是否合规
#         if s.is_valid():
#             s.save()
#             return Response(data=s.data, status=status.HTTP_201_CREATED)
#         return Response(s.errors, status=status.HTTP_400_BAD_REQUEST)

"""二、使用通用类视图编程 Generic Class Based View"""
# from rest_framework import generics
# from .models import myUser


# class CustomUserList(generics.ListCreateAPIView):
#     queryset = myUser.objects.all()
#     serializer_class = CustomUserSerializer


# class CusomUserDetail(generics.RetrieveUpdateDestroyAPIView):
#     queryset = myUser.objects.all()
#     serializer_class = CustomUserSerializer


"""三、使用视图集编程 Viewset"""
from rest_framework import viewsets
from .models import myUser


class CustomUserViewSet(viewsets.ModelViewSet):
    queryset = myUser.objects.all()
    serializer_class = CustomUserSerializer


"""# 定义注册新用户视图"""
from rest_framework import generics, permissions
from .serializers import RegisterSerializer


class RegisterView(generics.GenericAPIView):
    authentication_classes = []
    serializer_class = RegisterSerializer
    permission_classes = (permissions.AllowAny,)

    def post(self, request, *args, **kwargs):
        # 自动默认为新注册用户设置为普通角色
        request.data["role"] = "common"
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.save()
        print(user)
        print(user.role)
        return Response(
            {
                "user_id": user.id,
                "username": user.username,
                "email": user.email,
                "idcard": user.idcard,
                "company": user.company,
                "department": user.department,
                "workshop": user.workshop,
                "position": user.position,
                "area": user.area,
                "role": user.role,
                "base": user.base,
            },
            status=status.HTTP_201_CREATED,
        )


"""# 定义使用Django信号机制自动生成Token的函数"""
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.conf import settings
from rest_framework.authtoken.models import Token

"""创建用户时自动生成Token"""


@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def generate_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)


"""JWT登录视图"""
from rest_framework.views import APIView
from common import models
from common.utils.jwt_auth import create_token
from django.contrib import auth


class JwtLoginView(APIView):
    """基于JWT的用户登录"""

    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        user = request.data.get("username")
        pwd = request.data.get("password")
        # user_object = models.myUser.objects.filter(username=user, password=pwd).first()
        # 使用Django自带的认证系统
        user_object = auth.authenticate(request, username=user, password=pwd)
        # print({"id": user_object.id, "name": user_object.username})
        print(type(user_object))
        if not user_object:
            print({"code": 1000, "error": "用户名或密码错误！"})
            return Response(
                {
                    "state": False,
                    "info": "用户名或密码错误！ ₍ᐢ •͈ ༝ •͈ ᐢ₎♡",
                    "data": {"username": user},
                }
            )

        accessToken = create_token({"id": user_object.id, "name": user_object.username}, timeout=100)

        role = user_object.role
        is_see=user_object.is_see
        is_edit=user_object.is_edit
        is_delete=user_object.is_delete
        is_auditor=user_object.is_auditor
        company = user_object.company
        position = user_object.position       
        print(role)
        Response_role = []
        Response_role.append(role)
        # 用户权限
        Response_permission = []
        Response_permission.append(is_see)
        Response_permission.append(is_edit)
        Response_permission.append(is_delete)
        Response_permission.append(is_auditor)
        Response_permission.append(company)
        Response_permission.append(position)
        # 所属基地
        base = user_object.base

        return Response(
            {
                "state": True,
                "info":"登录成功！ <(￣︶￣)>",
                "data": {
                    "username": user_object.username,
                    "accessToken": accessToken,
                    "roles": Response_role,
                    "base": base,
                    "is_see": Response_permission[0],
                    "is_edit": Response_permission[1],
                    "is_delete": Response_permission[2],
                    "is_auditor": Response_permission[3],
                    "company": Response_permission[4],
                    "position": Response_permission[5],
                },
            }
        )


class JwtOrderView(APIView):
    """测试通过JWT认证获取某一个接口数据"""

    def get(self, request, *args, **kwargs):
        print(request.user)

        return Response("订单列表！获取成功！")


"""刷新Token接口"""


class RefreshTokenView(APIView):
    authentication_classes = []
    permission_classes = []

    def post(self, request, *args, **kwargs):
        refreshToken = request.data.get("refreshToken")
        if refreshToken:
            return Response(
                {
                    "state": True,
                    "data": {
                        "accessToken": "eyJhbGciOiJIUzUxMiJ9.newAdmin",
                        "refreshToken": "eyJhbGciOiJIUzUxMiJ9.newAdminRefresh",
                        # `expires`选择这种日期格式是为了方便调试，后端直接设置时间戳或许更方便（每次都应该递增）。如果后端返回的是时间戳格式，前端开发请来到这个目录`src/utils/auth.ts`，把第`38`行的代码换成expires = data.expires即可。
                        "expires": "2030/10/30 23:59:59",
                    },
                }
            )
        else:
            return Response({"success": False, "data": {}})


"""前端动态路由接口"""


class AsyncRoutesView(APIView):
    authentication_classes = []
    permission_classes = []
    permissionRouter = [
        {
            "path": "/permission",
            "meta": {"title": "menus.permission", "icon": "ep:lollipop", "rank": 199},
            "children": [
                {"path": "/permission/page/index", "name": "PermissionPage", "meta": {"title": "menus.permissionPage", "roles": ["super_admin"]}},
                {
                    "path": "/permission/button/index",
                    "name": "PermissionButton",
                    "meta": {
                        "title": "menus.permissionButton",
                        "showParent": "true",
                        "roles": ["super_admin"],
                        "auths": ["permission:btn:add", "permission:btn:edit", "permission:btn:delete"],
                    },
                },
                {
                    "path": "/permission/user_info_config/index",
                    "name": "user_info_config",
                    "meta": {
                        "title": "user_info_config",
                        "keepAlive": "true",
                        "showParent": "true",
                        "roles": ["admin","super_admin"]
                    }
                },
            ],
        },
    ]

    def get(self, request, *args, **kwargs):
        return Response({"success": True, "data": self.permissionRouter})
    
    
    
from rest_framework.schemas import AutoSchema
from coreapi import Field
import coreschema
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.exceptions import ObjectDoesNotExist
from datetime import date, datetime, timedelta, timezone
  
class UserInfoPermissionsViewCustomSchema(AutoSchema):
    """
    自定义的Schema类，用于处理myUser相关的序列化逻辑。

    这个类继承自AutoSchema，并根据需要重写或添加方法以处理特定的序列化需求。
    """

    def get_manual_fields(self, path, method):
        # 获取父类中已有的手动字段
        manual_fields = super().get_manual_fields(path, method)

        if method.lower() == "get":
            # 为 GET 请求添加查询参数
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="query",
                    schema=coreschema.Number(description="id"),
                ),
                
                Field(
                    name="username",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="用户名"),
                ),
                
                Field(
                    name="email",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="邮箱"),
                ),
                Field(
                    name="id_card",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="员工编号"),
                ),
                Field(
                    name="company",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="公司"),
                ),
                Field(
                    name="department",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="部门"),
                ),
                Field(
                    name="workshop",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="科室"),
                ),
                Field(
                    name="position",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="岗位"),
                ),
                Field(
                    name="is_see",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="是否可查看"),

                ),
                Field(
                    name="is_edit",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="是否可编辑"),

                ),
                Field(
                    name="is_delete",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="是否可删除"),

                ),
                Field(
                    name="role",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="角色"),
                ),
                Field(
                    name="base",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="基地"),
                ),
                Field(
                    name="last_login",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="最后登录时间"),

                ),
                Field(
                    name="date_joined",
                    required=False,
                    location="query",
                    schema=coreschema.String(description="注册时间"),
                ),
                
                
                # 更多查询参数...
            ]
        elif method.lower() == "patch":
            manual_fields = [
                Field(
                    name="id",
                    required=False,
                    location="form",
                    schema=coreschema.Number(description="id"),
                ),
                
                Field(
                    name="username",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="用户名"),
                ),
                Field(
                    name="email",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="邮箱"),
                ),
                Field(
                    name="id_card",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="员工编号"),
                ),
                Field(
                    name="company",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="公司"),
                ),
                Field(
                    name="department",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="部门"),
                ),
                Field(
                    name="workshop",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="科室"),
                ),
                Field(
                    name="position",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="岗位"),
                ),
                Field(
                    name="is_see",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="是否可查看"),

                ),
                Field(
                    name="is_edit",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="是否可编辑"),

                ),
                Field(
                    name="is_delete",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="是否可删除"),

                ),
                Field(
                    name="role",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="角色"),
                ),
                Field(
                    name="base",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="基地"),
                ),
                Field(
                    name="last_login",
                    required=False,
                    location="form",
                    schema=coreschema.String(description="最后登录时间"),

                ),
                
                # 更多查询参数...
            ]
        elif method.lower() == "delete":
            manual_fields = [
                Field(
                    name="id",
                    required=True,
                    location="query",
                    schema=coreschema.Number(description="id"),
                )
            ]
        return manual_fields

class UserInfoPermissionsView(APIView):
    """
    类说明：
        用于处理myUser表的数据，可以使用get，post，patch，delete方法
    方法：
        get:获取数据
        post:添加数据
        patch:部分更新数据
        delete:删除数据
    """

    # 设置默认的每页默认数据量
    page_size = 100000
    # 设置在API DOC的字段显示
    schema = UserInfoPermissionsViewCustomSchema()

    def get(self, request, *args, **kwargs):
        # 获取数据列表
        data_list = self.get_queryset(request)

        # 获取页码
        page = request.GET.get("page")

        # 根据URL参数可能提供的每页数据量来覆盖默认设置
        try:
            page_size = int(request.GET.get("page_size", self.page_size))
            print(page_size)
        except ValueError:
            page_size = self.page_size
            print(page_size)

        # 创建Paginator对象
        paginator = Paginator(data_list, page_size)  # page_size是每页显示的数量

        try:
            # 获取指定页的数据
            queryset_page = paginator.page(page)
        except PageNotAnInteger:
            # 如果页码不是一个整数，展示第一页
            queryset_page = paginator.page(1)
        except EmptyPage:
            # 如果页码超出范围(例如9999)，展示最后一页
            queryset_page = paginator.page(paginator.num_pages)

        # 序列化数据
        s = CustomUserSerializer(instance=queryset_page, many=True)
        return Response(s.data, status=status.HTTP_200_OK)
    def patch(self, request, *args, **kwargs):
        print(request.data)
        id = request.data["id"]
        try:
            instance = myUser.objects.get(id=id)
        except ObjectDoesNotExist:
            return Response({"error": "Object does not exist"}, status=404)

        serializer = CustomUserSerializer(instance, data=request.data, partial=True)
        if serializer.is_valid():
            # instance.material_add_time = datetime.now()
            serializer.save()
            return Response(serializer.data, status=200)
        return Response(serializer.errors, status=400)

    def delete(self, request, *args, **kwargs):
        id = request.query_params.get("id")
        try:
            instance = myUser.objects.get(id=id)
            instance.delete()
            return Response({"message": "删除成功！"}, status=status.HTTP_200_OK)
        except ObjectDoesNotExist:
            return Response({"error": "Object does not exist"}, status=status.HTTP_404_NOT_FOUND)

    def get_queryset(self, request, *args, **kwargs):
        # 这里实现获取数据集合的逻辑
        # 例如: return Model.objects.all()
        # 创建一个基础的查询集
        queryset = myUser.objects.filter().order_by("id")
        # 获取请求的参数
        id = request.query_params.get("id")
        username = request.query_params.get("username")
        idcard=request.query_params.get("idcard")
        company = request.query_params.get("company")
        department = request.query_params.get("department")
        workshop = request.query_params.get("workshop")
        position = request.query_params.get("position")
        is_see = request.query_params.get("is_see")
        is_edit = request.query_params.get("is_edit")
        is_delete = request.query_params.get("is_delete")
        role = request.query_params.get("role")
        base = request.query_params.get("base")
        
        # 根据参数是否存在添加不同筛选条件
        if id is not None:
            queryset = queryset.filter(id=id)
        if username is not None:
            queryset = queryset.filter(username=username)
        if idcard is not None:
            queryset = queryset.filter(idcard=idcard)
        if company is not None:
            queryset = queryset.filter(company=company)
        if department is not None:
            queryset = queryset.filter(department=department)
        if workshop is not None:
            queryset = queryset.filter(workshop=workshop)
        if position is not None:
            queryset = queryset.filter(position=position)
        if is_see is not None:
            queryset = queryset.filter(is_see=is_see)
        if is_edit is not None:
            queryset = queryset.filter(is_edit=is_edit)
        if is_delete is not None:
            queryset = queryset.filter(is_delete=is_delete)
        if role is not None:
            queryset = queryset.filter(role=role)
        if base is not None:
            queryset = queryset.filter(base=base)
        else:
            pass
        return queryset
